//
//  EmotionVC.swift
//  Emotion
//
//  Created by maker on 2016/11/19.
//  Copyright © 2016年 maker. All rights reserved.
//

import UIKit

private let EmotionCells = "EmotionCell"

class EmotionVC: UIViewController {
    
    fileprivate lazy var collectView : UICollectionView = UICollectionView(frame:CGRect(), collectionViewLayout: EmotionLayout())
    fileprivate lazy var tool : UIToolbar = UIToolbar()
    fileprivate lazy var manager : EmotionManager = EmotionManager()
    var callBack : (_ emotion : EmotionModel) -> ()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
    
    //父类时控制器,自定义构造方法必须实现super.init(nibName: nil, bundle: nil)
    init(callBack : @escaping (_ emotion : EmotionModel) -> ()) {
        self.callBack = callBack    //保存下闭包
        super.init(nibName: nil, bundle: nil)
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }


}

//MARK:==========设置 UI==========
extension EmotionVC {
    func setupUI() {
        //1.添加子控件
        view.addSubview(collectView)
        view.addSubview(tool)
        
        //2.设置子控件的属性
        collectView.backgroundColor = UIColor.purple
        
        //3.设置约束VFL
        collectView.translatesAutoresizingMaskIntoConstraints = false
        tool.translatesAutoresizingMaskIntoConstraints = false
        let views = ["toolBar" : tool,"collect":collectView] as [String : Any]
        
        var cons = NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[toolBar]-0-|", options: [], metrics: nil, views: views)
        cons += NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[collect]-0-[toolBar]-0-|", options: [.alignAllLeft,.alignAllRight], metrics: nil, views: views)
        view.addConstraints(cons)
        
        //4.设置 collectview
        prepareCollectView()
        
        //5.设置工具条
        prepareToolBar()
        
    }
    
    //设置集合视图
    fileprivate func prepareCollectView() {
        collectView.register(EmotionCell.self, forCellWithReuseIdentifier: EmotionCells)
        collectView.dataSource = self
        collectView.delegate = self
    }
    
    //准备工具条
    fileprivate func prepareToolBar(){
        let titles = ["最近","默认","emoji","浪小花"]
        var tempItem : [UIBarButtonItem] = [UIBarButtonItem]()
        
        var index = 0
        for title in titles {
            let item = UIBarButtonItem(title: title, style: .plain, target: self, action: #selector(EmotionVC.barClick(_:)))
            let filex = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
            item.tag = index
            tempItem.append(item)
            tempItem.append(filex)
            index += 1
        }
        tempItem.removeLast()
        tool.items = tempItem
        tool.tintColor = UIColor.orange
    }
}
//MARK:==========事件点击==========
extension EmotionVC{
    @objc fileprivate func barClick(_ sender:UIBarButtonItem){
        //1.根据按钮 tag 创建 indexpath
        let indexpath = IndexPath(item: 0, section: sender.tag)
        
        //2. 滚动
        collectView.scrollToItem(at: indexpath, at: .left, animated: true)
        
    }
}

//MARK:==========collectView 代理==========
extension EmotionVC: UICollectionViewDataSource,UICollectionViewDelegate{
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return manager.packages.count
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        let package = manager.packages[section]
        return package.emotions.count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: EmotionCells, for: indexPath) as! EmotionCell
        
        let package = manager.packages[indexPath.section]
        cell.model = package.emotions[indexPath.item]
        return cell
    }
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let package = manager.packages[indexPath.section]
        let model = package.emotions[indexPath.item]
        insertRecent(model)
        callBack(model)
    }
}

//MARK:==========插入最近表情==========
extension EmotionVC {
    func insertRecent(_ emotionModel : EmotionModel) {
        //1.如果是空白和删除直接返回
        if emotionModel.isEmpty || emotionModel.isDelete {
            return
        }
        
        //2.先移除表情
        let recentPackage = manager.packages.first!
        if (recentPackage.emotions.contains(emotionModel)){
            let index = recentPackage.emotions.index(of: emotionModel)!
            recentPackage.emotions.remove(at: index)
        }else{
            recentPackage.emotions.remove(at: 19)
        }
        
        //3.添加表情
        recentPackage.emotions.insert(emotionModel, at: 0)
        
    }
}
//MARK:==========自定义布局类==========
class EmotionLayout: UICollectionViewFlowLayout {
    override func prepare() {
        super.prepare()
        //1.计算 item 的宽度
        let itemW = screenWidth/7
        itemSize = CGSize(width: itemW, height: itemW)
        minimumLineSpacing = 0
        minimumInteritemSpacing = 0
        
        //2.设置 collectionView 的属性
        scrollDirection = .horizontal
        collectionView?.isPagingEnabled = true
        collectionView?.showsHorizontalScrollIndicator = false
        collectionView?.showsVerticalScrollIndicator = false
        
        let contentMargin = ((collectionView?.frame.size.height)! - 3*itemW)/2
        collectionView?.contentInset = UIEdgeInsetsMake(contentMargin, 0, contentMargin, 0)
    
    }
}













